<script setup name="TreeLeft">
import {getCurrentInstance, reactive} from "vue";

const {proxy} = getCurrentInstance();
const props = defineProps({
  // 在页面外面获取一次
  treeList: {
    type: Array,
    default: null,
  },
  //  关键字名称
  id: {
    type: String,
    default: "id"
  },
  // 树节点列名
  name: {
    type: String,
    default: "name"
  },
  // 树节点列名
  children: {
    type: String,
    default: "children"
  }
});

let pd = reactive({
  treeList: [],
  name: ""
});

/** 根据名称筛选树 */
watch(pd.name, val => {
  proxy.$refs["treeLeftRef"].filter(val);
});

watch(() => props.treeList, val => {
  initTreeLeft();
}, {deep: true, immediate: true});

// 初始化数据展示
function initTreeLeft() {
  if (pd.treeList.length > 0) {
    return;
  }
  if (props.treeList) {
    pd.treeList = props.treeList;
  }
}

/** 节点单击事件 */
function treeNodeClick(tree) {
  emit("ok", tree);
};

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const emit = defineEmits(["ok"]);

</script>
<template>
  <div class="head-container">
    <el-input v-model="pd.name" placeholder="请输入查询名称" clearable prefix-icon="Search"/>
  </div>
  <div class="head-container">
    <el-tree :data="pd.treeList" :props="{ label: props.name, children: props.children }" :expand-on-click-node="false"
             :filter-node-method="filterNode" ref="treeLeftRef" :node-key="props.id" highlight-current default-expand-all
             @node-click="treeNodeClick"/>
  </div>
</template>

<style scoped>

</style>